package com.asset.dispoal.business.bsEvidenceRecognition.service.commom;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.asset.dispoal.business.bsCase.domain.db.mapper.BsCaseMapper;
import com.asset.dispoal.business.idcardrefresh.domain.db.mapper.IdCardRefreshMapper;
import com.asset.dispoal.business.match.dto.MatchRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.springboot.protocol.Result;
import tech.mhuang.pacebox.springboot.redis.commands.IRedisExtCommands;

import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class IdCardExtraceCommand implements BaseCommand<MatchRequest, Result> {

    @Autowired
    IRedisExtCommands redisExtCommands;

    @Autowired
    IdCardRefreshMapper idCardRefreshMapper;

    @Autowired
    BsCaseMapper caseMapper;


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(MatchRequest matchRequest) {
        String requestKey = matchRequest.getData().getRequestKey();
        redisExtCommands.hdel(6, "idcard_before", requestKey);
        if (matchRequest.isFaild()) {
            idCardRefreshMapper.updateState(requestKey, "0");
            return Result.ok();
        }

        String responseKey = matchRequest.getData().getResponseKey();
        String notifyKey = responseKey + "_" + requestKey;
        String extractText = redisExtCommands.hget(6, "idcard_notify_key", notifyKey);
        JSONObject dataObject = JSON.parseObject(extractText);
        Set<String> caseIdSet = dataObject.keySet();
        for (String caseId : caseIdSet) {
            String matchStr = dataObject.getString(caseId);
            String regex = "\\d{4}.\\d{2}.\\d{2}-\\d{4}.\\d{2}.\\d{2}";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(matchStr);
            String result = null;
            String caseIdCardState = "0";
            if (matcher.find()) {
                String dateRange = matcher.group();
                result = dateRange.split("-")[1];
                idCardRefreshMapper.updateCaseResult(requestKey, caseId, result);
                caseIdCardState = "1";
            }
            caseMapper.updateIdCardState(caseId, result, caseIdCardState);
        }
        redisExtCommands.hdel(6, "idcard_notify_key", notifyKey);
        idCardRefreshMapper.updateState(requestKey, "1");
        return Result.ok();
    }
}
